package com.example.forestmanagement;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupMenu;
import android.widget.SearchView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polygon;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.forestmanagement.adapter.MarkListAdapter;
import com.example.forestmanagement.db.LocationDBHelper;
import com.example.forestmanagement.model.LocationPoint;
import com.example.forestmanagement.model.MarkData;
import com.example.forestmanagement.model.User;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements AMap.OnMapClickListener, AMap.OnMarkerClickListener, View.OnClickListener {
    private static final String TAG = "MainActivity";
    private static final String API_BASE_URL = "http://8.130.186.54:9898";
    private static final String API_UPDATE_LOCATION = API_BASE_URL + "/app-api/linban/user-track/create";
    private static final String API_BATCH_UPDATE_LOCATION = API_BASE_URL + "/app-api/linban/user-track/batch-create";

    private User currentUser;
    private LocationDBHelper dbHelper;
    private boolean isNetworkAvailable = true;

    private MapView mapView;
    private AMap aMap;
    private BottomNavigationView bottomNavigation;
    private SearchView searchView;
    private BottomSheetDialog drawToolsDialog;
    private BottomSheetDialog markListDialog;

    // 绘制相关变量
    private int currentDrawMode = 0; // 0: 无, 1: 点, 2: 线, 3: 面
    private int currentColor = Color.parseColor("#4285F4");
    private float currentWidth = 3.0f;
    private List<LatLng> drawPoints = new ArrayList<>();
    private Marker currentMarker;
    private Polyline currentPolyline;
    private Polygon currentPolygon;
    private EditText etMarkName, etMarkDesc;

    // 标注列表相关
    private List<MarkData> markList = new ArrayList<>();
    private List<Marker> loadedMarkers = new ArrayList<>();
    private List<Polyline> loadedPolylines = new ArrayList<>();
    private List<Polygon> loadedPolygons = new ArrayList<>();
    private MarkListAdapter markListAdapter;

    // 顶部提示文本
    private TextView tvDrawHint;
    private LinearLayout layoutDrawTools;
    private ImageButton btnUndo, btnRedo, btnClear;

    private OkHttpClient client = new OkHttpClient();
    private int userId = 1; // TODO: 从登录信息获取

    // 添加标注点ID映射
    private Map<String, MarkData> markerMap = new HashMap<>();

    private List<Marker> tempMarkers = new ArrayList<>();
    private Marker distanceMarker;

    private ImageButton btnLocation;
    private LatLng currentUserLocation;

    private Handler locationUpdateHandler = new Handler();
    private static final long LOCATION_UPDATE_INTERVAL = 5 * 60 * 1000; // 5分钟

    private Runnable locationUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            updateUserLocation();
            locationUpdateHandler.postDelayed(this, LOCATION_UPDATE_INTERVAL);
        }
    };

    private ImageButton btnMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        try {
            // 检查登录状态
//            if (!checkLoginStatus()) {
//                Intent intent = new Intent(this, LoginActivity.class);
//                startActivity(intent);
//                finish();
//                return;
//            }

            // 设置布局
            setContentView(R.layout.activity_main);

            // 初始化基础视图
            initBaseViews();

            // 初始化地图
            initMap(savedInstanceState);

            // 初始化定位按钮
            setupLocationButton();

            // 初始化功能
            initFeatures();

            // 加载标注列表
            loadMarkList();

            // 加载用户位置
            loadUserLocation();

            dbHelper = new LocationDBHelper(this);
            checkNetworkStatus();

            // 初始化当前用户
            SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
            int userId = sp.getInt("userId", 0);
            String username = sp.getString("username", "");
            currentUser = new User(userId, username);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "初始化失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            finish();
        }
    }

    private void initBaseViews() {
        bottomNavigation = findViewById(R.id.bottom_navigation);
        searchView = findViewById(R.id.searchView);
        tvDrawHint = findViewById(R.id.tv_draw_hint);
        layoutDrawTools = findViewById(R.id.layout_draw_tools);
        btnUndo = findViewById(R.id.btn_undo);
        btnRedo = findViewById(R.id.btn_redo);
        btnClear = findViewById(R.id.btn_clear);
        btnLocation = findViewById(R.id.btn_location);
        btnMenu = findViewById(R.id.btn_menu);
        btnMenu.setOnClickListener(v -> showNavigationMenu());
    }

    private void initMap(Bundle savedInstanceState) {
        mapView = findViewById(R.id.map_view);
        if (mapView != null) {
            mapView.onCreate(savedInstanceState);
            aMap = mapView.getMap();

            if (aMap != null) {
                // 设置卫星地图
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);

                // 自定义地图样式
                aMap.getUiSettings().setRotateGesturesEnabled(false); // 禁用旋转手势
                aMap.getUiSettings().setTiltGesturesEnabled(false);   // 禁用倾斜手势
                aMap.setMapType(AMap.MAP_TYPE_SATELLITE);             // 设置为卫星地图
                aMap.getUiSettings().setZoomControlsEnabled(true);    // 显示缩放按钮
                aMap.getUiSettings().setScaleControlsEnabled(true);   // 显示比例尺
                aMap.getUiSettings().setCompassEnabled(true);         // 显示指南针

                // 设置监听器
                aMap.setOnMapClickListener(this);
                aMap.setOnMarkerClickListener(this);
            } else {
                throw new RuntimeException("地图初始化失败");
            }
        } else {
            throw new RuntimeException("找不到地图视图");
        }
    }

    private void initFeatures() {
        if (bottomNavigation != null) {
            setupBottomNavigation();
        }
        if (searchView != null) {
            setupSearchView();
        }
        setupDrawTools();
        setupMapDrawTools();
        setupMarkList();
    }

    private boolean checkLoginStatus() {
        try {
            SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
            String token = sp.getString("token", null);
            userId = sp.getInt("userId", 0);

            if (token == null || userId == 0) {
                return false;
            }

            // 验证token是否有效
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private void setupMarkList() {
        markListDialog = new BottomSheetDialog(this);
        markListDialog.setContentView(R.layout.layout_mark_list);

        RecyclerView recyclerView = markListDialog.findViewById(R.id.recycler_marks);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        markListAdapter = new MarkListAdapter(markList, mark -> {
            try {
                JSONObject geometry = mark.getDataJson().getJSONObject("geometry");
                String type = geometry.getString("type");
                JSONArray coordinates = geometry.getJSONArray("coordinates");
                LatLng position = null;

                switch (type) {
                    case "Point":
                        // 对于点标注，直接获取坐标
                        double lng = coordinates.getDouble(0);
                        double lat = coordinates.getDouble(1);
                        position = new LatLng(lat, lng);
                        break;
                    case "LineString":
                        // 对于线段，取第一个点的坐标
                        JSONArray firstLinePoint = coordinates.getJSONArray(0);
                        position = new LatLng(firstLinePoint.getDouble(1), firstLinePoint.getDouble(0));
                        break;
                    case "Polygon":
                        // 对于多边形，取第一个环的第一个点的坐标
                        JSONArray ring = coordinates.getJSONArray(0);
                        JSONArray firstPolygonPoint = ring.getJSONArray(0);
                        position = new LatLng(firstPolygonPoint.getDouble(1), firstPolygonPoint.getDouble(0));
                        break;
                }

                if (position != null) {
                    // 移动地图到标注位置
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(position, 17));
                    // 关闭标注列表对话框
                    markListDialog.dismiss();
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(MainActivity.this, "跳转到标注位置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        recyclerView.setAdapter(markListAdapter);
    }

    private void loadMarkList() {
        SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
        String token = sp.getString("token", "");
        int userId = sp.getInt("userId", 0);

        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(API_BASE_URL + "/app-api/linban/label/list?userId=" + userId)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this,
                        "加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray data = jsonObject.getJSONArray("data");
                        List<MarkData> newMarkList = new ArrayList<>();

                        for (int i = 0; i < data.length(); i++) {
                            JSONObject item = data.getJSONObject(i);
                            MarkData mark = new MarkData();
                            mark.setId(item.getInt("id"));
                            mark.setLabelName(item.getString("labelName"));
                            mark.setLabelRemark(item.getString("labelRemark"));
                            mark.setDataJson(item.getJSONObject("dataJson"));
                            mark.setUserId(item.getInt("userId"));
                            mark.setCreateTime(item.getLong("createTime"));
                            mark.setUpdateTime(item.getLong("updateTime"));
                            newMarkList.add(mark);
                        }

                        runOnUiThread(() -> {
                            markList.clear();
                            markList.addAll(newMarkList);
                            markListAdapter.notifyDataSetChanged();
                            renderMarksOnMap();
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void renderMarksOnMap() {
        clearLoadedMarks();
        markerMap.clear();

        for (MarkData mark : markList) {
            try {
                JSONObject geometry = mark.getDataJson().getJSONObject("geometry");
                JSONObject properties = mark.getDataJson().getJSONObject("properties");
                String type = geometry.getString("type");
                JSONArray coordinates = geometry.getJSONArray("coordinates");
                int markColor = Color.parseColor(properties.getString("color"));
                float markWidth = (float) properties.getDouble("lineWidth");

                switch (type) {
                    case "Point":
                        double lng = coordinates.getDouble(0);
                        double lat = coordinates.getDouble(1);
                        addLabelMarker(new LatLng(lat, lng), mark);
                        break;

                    case "LineString":
                        List<LatLng> linePoints = new ArrayList<>();
                        for (int i = 0; i < coordinates.length(); i++) {
                            JSONArray point = coordinates.getJSONArray(i);
                            linePoints.add(new LatLng(point.getDouble(1), point.getDouble(0)));
                        }

                        // 添加线条
                        Polyline polyline = aMap.addPolyline(new PolylineOptions()
                                .addAll(linePoints)
                                .color(markColor)
                                .width(markWidth));
                        loadedPolylines.add(polyline);

                        // 显示每段线段的长度
                        for (int i = 0; i < linePoints.size() - 1; i++) {
                            LatLng start = linePoints.get(i);
                            LatLng end = linePoints.get(i + 1);
                            double distance = AMapUtils.calculateLineDistance(start, end);
                            LatLng center = new LatLng(
                                    (start.latitude + end.latitude) / 2,
                                    (start.longitude + end.longitude) / 2
                            );

                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(center)
                                    .title(String.format("%.1f米", distance))
                                    .anchor(0.5f, 0.5f);
                            Marker marker = aMap.addMarker(markerOptions);
                            marker.showInfoWindow();
                            loadedMarkers.add(marker);
                        }

                        // 显示总长度
                        if (properties.has("length")) {
                            double totalLength = properties.getDouble("length");
                            LatLng lastPoint = linePoints.get(linePoints.size() - 1);
                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(lastPoint)
                                    .title(String.format("总长: %.1f米", totalLength))
                                    .anchor(0f, 0f);
                            Marker marker = aMap.addMarker(markerOptions);
                            marker.showInfoWindow();
                            loadedMarkers.add(marker);
                        }
                        break;

                    case "Polygon":
                        JSONArray ring = coordinates.getJSONArray(0);
                        List<LatLng> polygonPoints = new ArrayList<>();
                        for (int i = 0; i < ring.length(); i++) {
                            JSONArray point = ring.getJSONArray(i);
                            polygonPoints.add(new LatLng(point.getDouble(1), point.getDouble(0)));
                        }

                        // 添加多边形
                        Polygon polygon = aMap.addPolygon(new PolygonOptions()
                                .addAll(polygonPoints)
                                .strokeColor(markColor)
                                .strokeWidth(markWidth)
                                .fillColor(Color.argb(50, Color.red(markColor),
                                        Color.green(markColor), Color.blue(markColor))));
                        loadedPolygons.add(polygon);

                        // 显示每条边的长度
                        for (int i = 0; i < polygonPoints.size(); i++) {
                            LatLng start = polygonPoints.get(i);
                            LatLng end = polygonPoints.get((i + 1) % polygonPoints.size());
                            double distance = AMapUtils.calculateLineDistance(start, end);
                            LatLng center = new LatLng(
                                    (start.latitude + end.latitude) / 2,
                                    (start.longitude + end.longitude) / 2
                            );

                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(center)
                                    .title(String.format("%.1f米", distance))
                                    .anchor(0.5f, 0.5f);
                            Marker marker = aMap.addMarker(markerOptions);
                            marker.showInfoWindow();
                            loadedMarkers.add(marker);
                        }

                        // 显示面积和周长
                        if (properties.has("area") && properties.has("perimeter")) {
                            double area = properties.getDouble("area");
                            double perimeter = properties.getDouble("perimeter");
                            LatLng center = calculatePolygonCenter(polygonPoints);

                            MarkerOptions markerOptions = new MarkerOptions()
                                    .position(center)
                                    .title(String.format("面积: %.1f平方米\n周长: %.1f米", area, perimeter))
                                    .anchor(0.5f, 0.5f);
                            Marker marker = aMap.addMarker(markerOptions);
                            marker.showInfoWindow();
                            loadedMarkers.add(marker);
                        }
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void addLabelMarker(LatLng position, MarkData mark) {
        MarkerOptions markerOptions = new MarkerOptions()
                .position(position)
                .title(mark.getLabelName())
                .snippet(mark.getLabelRemark())
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker))
                .anchor(0.5f, 1.0f);  // 将图标底部中心作为锚点

        Marker marker = aMap.addMarker(markerOptions);
        loadedMarkers.add(marker);
        markerMap.put(marker.getId(), mark);
    }

    private int getColorFromJson(JSONObject dataJson) {
        try {
            JSONObject properties = dataJson.getJSONObject("properties");
            String colorStr = properties.getString("color");
            if (colorStr != null && !colorStr.isEmpty()) {
                return Color.parseColor(colorStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Color.parseColor("#4285F4"); // 默认蓝色
    }

    private float getWidthFromJson(JSONObject dataJson) {
        try {
            JSONObject properties = dataJson.getJSONObject("properties");
            return (float) properties.getDouble("lineWidth");
        } catch (Exception e) {
            return 3.0f;
        }
    }

    private LatLng calculatePolygonCenter(List<LatLng> points) {
        double lat = 0, lng = 0;
        int size = points.size();
        for (LatLng point : points) {
            lat += point.latitude;
            lng += point.longitude;
        }
        return new LatLng(lat / size, lng / size);
    }

    private void clearLoadedMarks() {
        for (Marker marker : loadedMarkers) marker.remove();
        for (Polyline polyline : loadedPolylines) polyline.remove();
        for (Polygon polygon : loadedPolygons) polygon.remove();
        loadedMarkers.clear();
        loadedPolylines.clear();
        loadedPolygons.clear();
    }

    private void setupMapDrawTools() {
        btnUndo.setOnClickListener(this);
        btnRedo.setOnClickListener(this);
        btnClear.setOnClickListener(this);
    }

    private void setupBottomNavigation() {
        bottomNavigation.setOnItemSelectedListener(item -> {
            int id = item.getItemId();
            if (id == R.id.navigation_map) {
                hideDrawTools();
                return true;
            } else if (id == R.id.navigation_marks) {
                markListDialog.show();
                return true;
            } else if (id == R.id.navigation_draw) {
                showDrawTools();
                return true;
            } else if (id == R.id.navigation_command) {
                startActivity(new Intent(this, CommandCenterActivity.class));
                return true;
            }
            return false;
        });
    }

    private void setupSearchView() {
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                startActivity(new Intent(MainActivity.this, HistoryDataActivity.class));
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });
    }

    private void setupDrawTools() {
        drawToolsDialog = new BottomSheetDialog(this);
        drawToolsDialog.setContentView(R.layout.layout_draw_tools);

        drawToolsDialog.findViewById(R.id.btn_marker).setOnClickListener(v -> {
            clearCurrentDrawing();
            currentDrawMode = 1;
            updateDrawHint("点击地图添加标记点");
            drawToolsDialog.dismiss();
            showMapDrawTools();
        });

        drawToolsDialog.findViewById(R.id.btn_polyline).setOnClickListener(v -> {
            clearCurrentDrawing();
            currentDrawMode = 2;
            updateDrawHint("点击地图绘制折线，双击结束绘制");
            drawPoints.clear();
            drawToolsDialog.dismiss();
            showMapDrawTools();
        });

        drawToolsDialog.findViewById(R.id.btn_polygon).setOnClickListener(v -> {
            clearCurrentDrawing();
            currentDrawMode = 3;
            updateDrawHint("点击地图绘制多边形，双击结束绘制");
            drawPoints.clear();
            drawToolsDialog.dismiss();
            showMapDrawTools();
        });

        // 设置初始选中的颜色
        View[] colorViews = new View[5];
        colorViews[0] = drawToolsDialog.findViewById(R.id.color_blue);
        colorViews[1] = drawToolsDialog.findViewById(R.id.color_light_blue);
        colorViews[2] = drawToolsDialog.findViewById(R.id.color_green);
        colorViews[3] = drawToolsDialog.findViewById(R.id.color_yellow);
        colorViews[4] = drawToolsDialog.findViewById(R.id.color_red);

        // 设置初始背景
        colorViews[0].setBackgroundResource(R.drawable.circle_color_selected);
        colorViews[0].setBackgroundResource(R.drawable.circle_color_blue);
        colorViews[1].setBackgroundResource(R.drawable.circle_color_light_blue);
        colorViews[2].setBackgroundResource(R.drawable.circle_color_green);
        colorViews[3].setBackgroundResource(R.drawable.circle_color_yellow);
        colorViews[4].setBackgroundResource(R.drawable.circle_color_red);

        // 更新颜色选择反馈
        View.OnClickListener colorClickListener = v -> {
            // 重置所有颜色选择的边框
            for (View colorView : colorViews) {
                if (colorView == v) {
                    colorView.setBackgroundResource(R.drawable.circle_color_selected);
                } else {
                    // 根据不同的View设置对应的背景
                    if (colorView == colorViews[0]) {
                        colorView.setBackgroundResource(R.drawable.circle_color_blue);
                    } else if (colorView == colorViews[1]) {
                        colorView.setBackgroundResource(R.drawable.circle_color_light_blue);
                    } else if (colorView == colorViews[2]) {
                        colorView.setBackgroundResource(R.drawable.circle_color_green);
                    } else if (colorView == colorViews[3]) {
                        colorView.setBackgroundResource(R.drawable.circle_color_yellow);
                    } else if (colorView == colorViews[4]) {
                        colorView.setBackgroundResource(R.drawable.circle_color_red);
                    }
                }
            }

            if (v.getId() == R.id.color_blue) currentColor = Color.parseColor("#4285F4");
            else if (v.getId() == R.id.color_light_blue) currentColor = Color.parseColor("#03A9F4");
            else if (v.getId() == R.id.color_green) currentColor = Color.parseColor("#4CAF50");
            else if (v.getId() == R.id.color_yellow) currentColor = Color.parseColor("#FFC107");
            else if (v.getId() == R.id.color_red) currentColor = Color.parseColor("#F44336");

            updateCurrentDrawable();
        };

        drawToolsDialog.findViewById(R.id.color_blue).setOnClickListener(colorClickListener);
        drawToolsDialog.findViewById(R.id.color_light_blue).setOnClickListener(colorClickListener);
        drawToolsDialog.findViewById(R.id.color_green).setOnClickListener(colorClickListener);
        drawToolsDialog.findViewById(R.id.color_yellow).setOnClickListener(colorClickListener);
        drawToolsDialog.findViewById(R.id.color_red).setOnClickListener(colorClickListener);

        SeekBar widthSeekBar = drawToolsDialog.findViewById(R.id.seekbar_width);
        widthSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                currentWidth = progress + 1;
                updateCurrentDrawable();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        Button btnSave = drawToolsDialog.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(v -> saveDrawing());

        Button btnCancel = drawToolsDialog.findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(v -> {
            clearCurrentDrawing();
            drawToolsDialog.dismiss();
            hideDrawTools();
        });

        etMarkName = drawToolsDialog.findViewById(R.id.et_mark_name);
        etMarkDesc = drawToolsDialog.findViewById(R.id.et_mark_desc);
    }

    private void showDrawTools() {
        drawToolsDialog.show();
    }

    private void showMapDrawTools() {
        tvDrawHint.setVisibility(View.VISIBLE);
        layoutDrawTools.setVisibility(View.VISIBLE);
    }

    private void hideDrawTools() {
        currentDrawMode = 0;
        tvDrawHint.setVisibility(View.GONE);
        layoutDrawTools.setVisibility(View.GONE);
        clearCurrentDrawing();
    }

    private void updateDrawHint(String hint) {
        tvDrawHint.setText(hint);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_undo) {
            undoLastPoint();
        } else if (id == R.id.btn_redo) {
            // TODO: 实现重做功能
        } else if (id == R.id.btn_clear) {
            clearCurrentDrawing();
        }
    }

    private void undoLastPoint() {
        if (drawPoints.size() > 0) {
            drawPoints.remove(drawPoints.size() - 1);
            updateCurrentDrawable();
        }
    }

    @Override
    public void onMapClick(LatLng latLng) {
        if (currentDrawMode == 0) return;

        // 清除之前的临时标记
        clearTempMarkers();

        switch (currentDrawMode) {
            case 1: // 点
                if (currentMarker != null) currentMarker.remove();
                currentMarker = aMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_marker))
                        .anchor(0.5f, 1.0f)  // 将图标底部中心作为锚点
                        .draggable(true));
                drawPoints.clear();
                drawPoints.add(latLng);
                showSaveDialog();
                break;
            case 2: // 线
                drawPoints.add(latLng);

                // 添加顶点标记
                Marker vertexMarker = aMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_vertex))
                        .anchor(0.5f, 0.5f));
                tempMarkers.add(vertexMarker);

                if (currentPolyline != null) currentPolyline.remove();
                if (drawPoints.size() > 1) {
                    // 绘制线
                    currentPolyline = aMap.addPolyline(new PolylineOptions()
                            .addAll(drawPoints)
                            .color(currentColor)
                            .width(currentWidth)
                            .useGradient(true));  // 使用渐变效果使线条更平滑

                    // 更新距离信息
                    updatePolylineDistance();
                }
                break;
            case 3: // 面
                drawPoints.add(latLng);

                // 添加顶点标记
                Marker polygonVertex = aMap.addMarker(new MarkerOptions()
                        .position(latLng)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_vertex))
                        .anchor(0.5f, 0.5f));
                tempMarkers.add(polygonVertex);

                if (currentPolygon != null) currentPolygon.remove();
                if (drawPoints.size() > 2) {
                    // 计算填充颜色
                    int fillColor = Color.argb(128,
                            Color.red(currentColor),
                            Color.green(currentColor),
                            Color.blue(currentColor));

                    // 绘制多边形
                    currentPolygon = aMap.addPolygon(new PolygonOptions()
                            .addAll(drawPoints)
                            .strokeColor(currentColor)
                            .strokeWidth(currentWidth)
                            .fillColor(fillColor));

                    // 更新面积和周长信息
                    updatePolygonMeasurements();
                }
                break;
        }
    }

    private void showSaveDialog() {
        if (drawPoints.size() < 1) return;

        if (currentDrawMode == 1 ||
                (currentDrawMode == 2 && drawPoints.size() > 1) ||
                (currentDrawMode == 3 && drawPoints.size() > 2)) {
            drawToolsDialog.show();
        }
    }

    private void updateCurrentDrawable() {
        if (currentPolyline != null) {
            currentPolyline.remove();
            if (drawPoints.size() > 1) {
                currentPolyline = aMap.addPolyline(new PolylineOptions()
                        .addAll(drawPoints)
                        .color(currentColor)
                        .width(currentWidth));
            }
        }
        if (currentPolygon != null) {
            currentPolygon.remove();
            if (drawPoints.size() > 2) {
                currentPolygon = aMap.addPolygon(new PolygonOptions()
                        .addAll(drawPoints)
                        .strokeColor(currentColor)
                        .strokeWidth(currentWidth)
                        .fillColor(Color.argb(128, Color.red(currentColor),
                                Color.green(currentColor), Color.blue(currentColor))));
            }
        }
    }

    private void clearCurrentDrawing() {
        if (currentMarker != null) currentMarker.remove();
        if (currentPolyline != null) currentPolyline.remove();
        if (currentPolygon != null) currentPolygon.remove();
        drawPoints.clear();
    }

    private void saveDrawing() {
        if (drawPoints.isEmpty()) {
            Toast.makeText(this, "请先绘制图形", Toast.LENGTH_SHORT).show();
            return;
        }

        String name = etMarkName.getText().toString();
        String desc = etMarkDesc.getText().toString();

        if (name.isEmpty()) {
            Toast.makeText(this, "请输入标注名称", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            JSONObject geojson = new JSONObject();
            geojson.put("type", "Feature");

            JSONObject properties = new JSONObject();
            properties.put("color", String.format("#%06X", (0xFFFFFF & currentColor)));
            properties.put("lineWidth", currentWidth);
            properties.put("title", name);
            properties.put("description", desc);

            // 添加面积和周长的保存
            if (currentDrawMode == 3 && drawPoints.size() > 2) {
                double area = AMapUtils.calculateArea(drawPoints);
                double perimeter = 0;
                for (int i = 0; i < drawPoints.size(); i++) {
                    LatLng p1 = drawPoints.get(i);
                    LatLng p2 = drawPoints.get((i + 1) % drawPoints.size());
                    perimeter += AMapUtils.calculateLineDistance(p1, p2);
                }
                properties.put("area", area);
                properties.put("perimeter", perimeter);
            } else if (currentDrawMode == 2 && drawPoints.size() > 1) {
                // 保存线段总长度
                double totalLength = 0;
                for (int i = 0; i < drawPoints.size() - 1; i++) {
                    totalLength += AMapUtils.calculateLineDistance(drawPoints.get(i), drawPoints.get(i + 1));
                }
                properties.put("length", totalLength);
            }

            geojson.put("properties", properties);

            JSONObject geometry = new JSONObject();
            switch (currentDrawMode) {
                case 1:
                    geometry.put("type", "Point");
                    JSONArray coordinates = new JSONArray();
                    coordinates.put(drawPoints.get(0).longitude);
                    coordinates.put(drawPoints.get(0).latitude);
                    geometry.put("coordinates", coordinates);
                    break;
                case 2:
                    geometry.put("type", "LineString");
                    JSONArray lineCoords = new JSONArray();
                    for (LatLng point : drawPoints) {
                        JSONArray coord = new JSONArray();
                        coord.put(point.longitude);
                        coord.put(point.latitude);
                        lineCoords.put(coord);
                    }
                    geometry.put("coordinates", lineCoords);
                    break;
                case 3:
                    geometry.put("type", "Polygon");
                    JSONArray polygonCoords = new JSONArray();
                    JSONArray ring = new JSONArray();
                    for (LatLng point : drawPoints) {
                        JSONArray coord = new JSONArray();
                        coord.put(point.longitude);
                        coord.put(point.latitude);
                        ring.put(coord);
                    }
                    // 闭合多边形
                    if (!drawPoints.get(0).equals(drawPoints.get(drawPoints.size() - 1))) {
                        JSONArray coord = new JSONArray();
                        coord.put(drawPoints.get(0).longitude);
                        coord.put(drawPoints.get(0).latitude);
                        ring.put(coord);
                    }
                    polygonCoords.put(ring);
                    geometry.put("coordinates", polygonCoords);
                    break;
            }
            geojson.put("geometry", geometry);

            // 创建请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("labelName", name);
            requestBody.put("labelRemark", desc);
            requestBody.put("dataJson", geojson);
            requestBody.put("userId", userId);

            SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
            String token = sp.getString("token", "");

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody.toString());
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(API_BASE_URL + "/app-api/linban/label/create")
                    .addHeader("Authorization", "Bearer " + token)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this,
                            "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String responseData = response.body().string();
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getInt("code") == 0) {
                            runOnUiThread(() -> {
                                Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                                clearCurrentDrawing();
                                drawToolsDialog.dismiss();
                                hideDrawTools();
                                etMarkName.setText("");
                                etMarkDesc.setText("");
                                // 重新加载标注列表，但保持用户标注
                                loadMarkList();
                                loadUserLocation(); // 重新加载用户位置
                            });
                        } else {
                            runOnUiThread(() -> {
                                try {
                                    Toast.makeText(MainActivity.this,
                                            "保存失败: " + jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            });
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        runOnUiThread(() -> Toast.makeText(MainActivity.this,
                                "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }
            });

        } catch (Exception e) {
            Toast.makeText(this, "保存失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void clearTempMarkers() {
        for (Marker marker : tempMarkers) {
            marker.remove();
        }
        tempMarkers.clear();
        if (distanceMarker != null) {
            distanceMarker.remove();
            distanceMarker = null;
        }
    }

    private void updatePolylineDistance() {
        if (drawPoints.size() < 2) return;

        // 计算总长度
        double totalLength = 0;
        for (int i = 0; i < drawPoints.size() - 1; i++) {
            totalLength += AMapUtils.calculateLineDistance(drawPoints.get(i), drawPoints.get(i + 1));
        }

        // 在最新线段的中点显示距离
        LatLng lastPoint = drawPoints.get(drawPoints.size() - 1);
        LatLng prevPoint = drawPoints.get(drawPoints.size() - 2);
        LatLng center = new LatLng(
                (lastPoint.latitude + prevPoint.latitude) / 2,
                (lastPoint.longitude + prevPoint.longitude) / 2
        );

        String distanceInfo = String.format("总长: %.2f米", totalLength);

        if (distanceMarker != null) {
            distanceMarker.remove();
        }

        distanceMarker = aMap.addMarker(new MarkerOptions()
                .position(center)
                .title(distanceInfo)
                .visible(true));
        distanceMarker.showInfoWindow();
        tempMarkers.add(distanceMarker);
    }

    private void updatePolygonMeasurements() {
        if (drawPoints.size() < 3) return;

        // 计算面积
        double area = AMapUtils.calculateArea(drawPoints);

        // 计算周长
        double perimeter = 0;
        for (int i = 0; i < drawPoints.size(); i++) {
            LatLng p1 = drawPoints.get(i);
            LatLng p2 = drawPoints.get((i + 1) % drawPoints.size());
            perimeter += AMapUtils.calculateLineDistance(p1, p2);
        }

        // 在多边形中心显示信息
        LatLng center = calculatePolygonCenter(drawPoints);
        String measureInfo = String.format("面积: %.1f平方米\n周长: %.2f米", area, perimeter);

        if (distanceMarker != null) {
            distanceMarker.remove();
        }

        distanceMarker = aMap.addMarker(new MarkerOptions()
                .position(center)
                .title(measureInfo)
                .visible(true));
        distanceMarker.showInfoWindow();
        tempMarkers.add(distanceMarker);
    }

    private void loadUserLocation() {
        SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
        String token = sp.getString("token", "");
        int userId = sp.getInt("userId", 0);

        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(API_BASE_URL + "/app-api/linban/user/get?id=" + userId)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this,
                        "获取位置失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        int jobGroupId = data.getInt("jobGroupId");

                        // 保存当前用户位置
                        currentUserLocation = new LatLng(
                                data.getDouble("latitude"),
                                data.getDouble("longitude")
                        );

                        // 加载当前用户位置
                        addUserMarker(data);

                        // 加载同组用户
                        loadGroupUsers(jobGroupId, token);

                        // 移动地图到当前用户位置
                        runOnUiThread(() -> {
                            if (currentUserLocation != null) {
                                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentUserLocation, 15));
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this,
                                "解析用户位置数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
            }
        });
    }

    private void loadGroupUsers(int jobGroupId, String token) {
        okhttp3.Request request = new okhttp3.Request.Builder()
                .url(API_BASE_URL + "/app-api/linban/user/list?jobGroupId=" + jobGroupId)
                .addHeader("Authorization", "Bearer " + token)
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this,
                        "获取同组用户失败: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);
                    if (jsonObject.getInt("code") == 0) {
                        JSONArray users = jsonObject.getJSONArray("data");
                        for (int i = 0; i < users.length(); i++) {
                            JSONObject user = users.getJSONObject(i);
                            addUserMarker(user);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void addUserMarker(JSONObject userInfo) throws JSONException {
        runOnUiThread(() -> {
            try {
                LatLng location = new LatLng(
                        userInfo.getDouble("latitude"),
                        userInfo.getDouble("longitude")
                );

                // 创建自定义信息窗口的布局
                View markerView = getLayoutInflater().inflate(R.layout.marker_user_info, null);
                TextView tvName = markerView.findViewById(R.id.tv_user_name);
                TextView tvJob = markerView.findViewById(R.id.tv_user_job);

                tvName.setText(userInfo.getString("userName"));
                tvJob.setText(userInfo.getString("job"));

                // 将布局转换为Bitmap
                markerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                markerView.layout(0, 0, markerView.getMeasuredWidth(), markerView.getMeasuredHeight());
                markerView.setDrawingCacheEnabled(true);
                markerView.buildDrawingCache();
                Bitmap bmp = Bitmap.createBitmap(markerView.getDrawingCache());
                markerView.setDrawingCacheEnabled(false);

                // 添加标记
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(location)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_user_location))
                        .anchor(0.5f, 1.0f) // 设置图标底部中心为锚点
                        .title(userInfo.getString("userName"))
                        .snippet(userInfo.getString("job"));

                Marker marker = aMap.addMarker(markerOptions);
                marker.setObject(userInfo.toString());
                loadedMarkers.add(marker);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        // 检查是否是临时标记点
        if (tempMarkers.contains(marker) || marker.equals(distanceMarker)) {
            return true;
        }

        // 获取标记点对应的数据
        MarkData markData = markerMap.get(marker.getId());
        if (markData != null) {
            Toast.makeText(this, "标记点: " + markData.getLabelName(), Toast.LENGTH_SHORT).show();
            return true;
        }

        // 处理用户标记点点击
        try {
            String userInfoStr = (String) marker.getObject();
            if (userInfoStr != null) {
                JSONObject userInfo = new JSONObject(userInfoStr);
                showUserTrackDialog(userInfo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    private void showUserTrackDialog(JSONObject userInfo) {
        try {
            // 创建对话框布局
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            View dialogView = getLayoutInflater().inflate(R.layout.dialog_user_info, null);

            // 设置用户信息
            TextView tvUserName = dialogView.findViewById(R.id.tv_user_name);
            TextView tvUserJob = dialogView.findViewById(R.id.tv_user_job);
            TextView tvUserGroup = dialogView.findViewById(R.id.tv_user_group);
            TextView tvUserAccount = dialogView.findViewById(R.id.tv_user_account);
            TextView tvUserStatus = dialogView.findViewById(R.id.tv_user_status);
            TextView tvLastActive = dialogView.findViewById(R.id.tv_last_active);

            tvUserName.setText("姓名: " + userInfo.getString("userName"));
            tvUserJob.setText("职位: " + userInfo.getString("job"));
            tvUserGroup.setText("工作组: " + userInfo.getString("jobGroup"));
            tvUserAccount.setText("账号: " + userInfo.getString("account"));
            tvUserStatus.setText("状态: " + (userInfo.getInt("isAlive") == 1 ? "在线" : "离线"));

            // 格式化最后活跃时间
            long lastAliveTime = userInfo.getLong("lastAliveTime");
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String lastActiveStr = sdf.format(new java.util.Date(lastAliveTime));
            tvLastActive.setText("最后活跃: " + lastActiveStr);

            builder.setView(dialogView)
                    .setTitle("用户详情")
                    .setPositiveButton("查看24小时轨迹", (dialog, which) -> {
                        try {
                            Intent intent = new Intent(this, TrackPlaybackActivity.class);
                            intent.putExtra("userId", userInfo.getInt("id")); // 使用id字段
                            intent.putExtra("userName", userInfo.getString("userName"));
                            startActivity(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Toast.makeText(this, "获取用户ID失败", Toast.LENGTH_SHORT).show();
                        }
                    })
                    .setNegativeButton("关闭", null)
                    .show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "获取用户信息失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void setupLocationButton() {
        if (btnLocation != null) {
            btnLocation.setOnClickListener(v -> {
                if (currentUserLocation != null) {
                    // 使用动画效果移动到用户位置
                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentUserLocation, 15));
                } else {
                    Toast.makeText(this, "未获取到用户位置", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private void startLocationUpdates() {
        locationUpdateHandler.post(locationUpdateRunnable);
    }

    private void stopLocationUpdates() {
        locationUpdateHandler.removeCallbacks(locationUpdateRunnable);
    }

    private void updateUserLocation() {
        if (currentUserLocation == null) return;

        try {
            JSONObject requestBody = new JSONObject();
            requestBody.put("userId", userId);
            requestBody.put("latitude", currentUserLocation.latitude);
            requestBody.put("longitude", currentUserLocation.longitude);

            SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
            String token = sp.getString("token", "");

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody.toString());
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(API_UPDATE_LOCATION)
                    .addHeader("Authorization", "Bearer " + token)
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String responseData = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseData);
                        if (jsonResponse.getInt("code") != 0) {
                            System.out.println("更新位置失败: " + jsonResponse.getString("msg"));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }
        startLocationUpdates();
        // 检查网络状态
        checkNetworkStatus();
        // 尝试同步离线位置
        syncOfflineLocations();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mapView != null) {
            mapView.onPause();
        }
        stopLocationUpdates();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearTempMarkers();
        if (mapView != null) {
            mapView.onDestroy();
        }
        stopLocationUpdates();
        locationUpdateHandler.removeCallbacksAndMessages(null);
        if (dbHelper != null) {
            dbHelper.close();
        }
    }

    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    private void showNavigationMenu() {
        PopupMenu popup = new PopupMenu(this, btnMenu);
        popup.getMenuInflater().inflate(R.menu.navigation_menu, popup.getMenu());

        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.menu_profile) {
                // 打开个人资料页面
                startActivity(new Intent(MainActivity.this, ProfileActivity.class));
                return true;
            } else if (itemId == R.id.menu_settings) {
                // 打开设置页面
                startActivity(new Intent(MainActivity.this, SettingsActivity.class));
                return true;
            } else if (itemId == R.id.menu_logout) {
                // 退出登录
                logout();
                return true;
            }
            return false;
        });

        popup.show();
    }

    private void logout() {
        // 清除用户数据
        SharedPreferences.Editor editor = getSharedPreferences("user_info", MODE_PRIVATE).edit();
        editor.clear();
        editor.apply();

        // 返回登录页面
        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void checkNetworkStatus() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        isNetworkAvailable = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }

    private void updateLocation(double latitude, double longitude) {
        if (isNetworkAvailable) {
            // 尝试直接上传位置
            uploadLocation(latitude, longitude);
        } else {
            // 网络不可用时保存到本地数据库
            saveLocationToDB(latitude, longitude);
        }
    }

    private void uploadLocation(double latitude, double longitude) {
        try {
            JSONObject requestBody = new JSONObject();
            requestBody.put("userId", currentUser.getId());
            requestBody.put("latitude", latitude);
            requestBody.put("longitude", longitude);

            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody.toString());
            okhttp3.Request request = new okhttp3.Request.Builder()
                    .url(API_UPDATE_LOCATION)
                    .addHeader("Authorization", "Bearer " + getSharedPreferences("user_info", MODE_PRIVATE).getString("token", ""))
                    .post(body)
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    // 上传失败时保存到本地数据库
                    saveLocationToDB(latitude, longitude);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        String responseData = response.body().string();
                        JSONObject jsonResponse = new JSONObject(responseData);
                        if (jsonResponse.getInt("code") == 0) {
                            Log.d(TAG, "位置更新成功");
                        } else {
                            // API返回错误时也保存到本地数据库
                            saveLocationToDB(latitude, longitude);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        saveLocationToDB(latitude, longitude);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            saveLocationToDB(latitude, longitude);
        }
    }

    private void saveLocationToDB(double latitude, double longitude) {
        LocationPoint point = new LocationPoint(currentUser.getId(), latitude, longitude);
        dbHelper.addLocation(point);
        Log.d(TAG, "位置已保存到本地数据库");
    }

    private void syncOfflineLocations() {
        if (!isNetworkAvailable) {
            return;
        }

        List<LocationPoint> unsyncedLocations = dbHelper.getUnsyncedLocations();
        if (unsyncedLocations.isEmpty()) {
            return;
        }

        // 构建批量上传的请求参数
        JSONArray locationsArray = new JSONArray();
        for (LocationPoint point : unsyncedLocations) {
            JSONObject location = new JSONObject();
            try {
                location.put("userId", point.getUserId());
                location.put("latitude", point.getLatitude());
                location.put("longitude", point.getLongitude());
                location.put("timestamp", point.getCreateTime());
                locationsArray.put(location);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        JSONObject params = new JSONObject();
        try {
            params.put("locations", locationsArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // 发送批量位置更新请求
        StringRequest request = new StringRequest(Request.Method.POST, API_BATCH_UPDATE_LOCATION,
                response -> {
                    try {
                        JSONObject jsonResponse = new JSONObject(response);
                        if (jsonResponse.getInt("code") == 0) {
                            // 批量上传成功，标记为已同步
                            for (LocationPoint point : unsyncedLocations) {
                                dbHelper.markLocationAsSynced(point.getId());
                            }
                            Log.d(TAG, "离线位置同步成功");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                },
                error -> {
                    Log.e(TAG, "离线位置同步失败: " + error.getMessage());
                }) {
            @Override
            public byte[] getBody() {
                return params.toString().getBytes();
            }

            @Override
            public String getBodyContentType() {
                return "application/json";
            }
        };

        // 添加到请求队列
        Volley.newRequestQueue(this).add(request);
    }
} 